/*  Copyright (c) 2012 William Rogers and James Boud

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

using System;
using System.Text;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using Color = Microsoft.Xna.Framework.Color;
using SlimDX;
using SlimDX.Direct3D11;
using JBBRXG11;
using JBBRXG11ContentFBXModel;
using JBBRXG11ContentSpriteFont;
using JBBRXG11ContentTexture;

namespace JBBRXG11
{
    public class SpriteFont : Microsoft.Xna.Framework.Content.ContentTypeReader<SpriteFont>, IDisposable
    {
        ReadOnlyCollection<char> characters;
        int linespacing;
        float spacing;
        bool havedefaultchar;
        char defaultchar;

        // These handles are just kept because this class is responsible 
        // for disposing the texture.  For use they are wrapped in a Texture2D
        SlimDX.Direct3D11.Texture2D dxtexture;
        ShaderResourceView dxtextureview;

        // These items are used for writing strings, etc
        Texture2D texture;
        charinfo[] chardata;
        int firstch, lastch;
        int[] charindex;

        internal Texture2D Texture { get { return texture; } }
        internal charinfo[] CharData { get { return chardata; } }
        internal int FirstCh { get { return firstch; } }
        internal int LastCh { get { return lastch; } }
        internal int[] CharIndex { get { return charindex; } }

        public ReadOnlyCollection<char> Characters { get { return characters; } }

        public char? DefaultCharacter
        {
            get
            {
                if (havedefaultchar)
                    return new char?(defaultchar);
                else
                    return new char?();
            }
            set
            {
                havedefaultchar = false;
                defaultchar = characters[0];
                if (value != null)
                {
                    for (int c = 1; c < chardata.Length; c++)
                    {
                        if (chardata[c].ch == (char)value)
                        {
                            chardata[0] = chardata[c];
                            havedefaultchar = true;
                            defaultchar = (char)value;
                            return;
                        }
                    }
                    throw new Exception("Cannot use " + ((char)value).ToString()
                                      + " as default character as it isn't in the font");
                }
            }
        }

        public int LineSpacing { get { return linespacing; } set { linespacing = value; } }

        public float Spacing { get { return spacing; } set { spacing = value; } }

        protected override SpriteFont Read(Microsoft.Xna.Framework.Content.ContentReader input,
                                           SpriteFont existingInstance)
        {
            FontInfoStuff fis = new FontInfoStuff();
            int chardatalength = input.ReadInt32();
            fis.chardata = new charinfo[chardatalength];
            for (int c = 0; c < chardatalength; c++)
            {
                fis.chardata[c].ch = input.ReadChar();
                fis.chardata[c].x = input.ReadInt32();
                fis.chardata[c].y = input.ReadInt32();
                fis.chardata[c].width = input.ReadInt32();
                fis.chardata[c].height = input.ReadInt32();
                fis.chardata[c].stride = input.ReadSingle();
            }
            int texdatalength = input.ReadInt32();
            fis.texturedata = input.ReadBytes(texdatalength);
            fis.texturewidth = input.ReadInt32();
            fis.textureheight = input.ReadInt32();
            fis.FontName = input.ReadString();
            fis.spacing = input.ReadSingle();
            fis.linespacing = input.ReadInt32();
            fis.havedefaultchar = input.ReadBoolean();
            fis.defaultcharindex = input.ReadInt32();
            // Can't use this instance as it belongs to the content manager
            // which may reuse it, overwriting this object
            SpriteFont newspritefont = new SpriteFont();
            GraphicsDeviceManager.GetGame(Game.GraphicsDevice).UserContentAdd(newspritefont);
            newspritefont.ProcessInfo(Game.GraphicsDevice, fis);
            return newspritefont;
        }

        public SpriteFont() { }

        void ProcessInfo(GraphicsDevice device, FontInfoStuff fis)
        {
            chardata = fis.chardata;
            List<char> chars = new List<char>();
            for (int c = 1; c < fis.chardata.Length; c++)
            {
                chars.Add(fis.chardata[c].ch);
            }
            characters = new ReadOnlyCollection<char>(chars);
            linespacing = fis.linespacing;
            spacing = fis.spacing;
            havedefaultchar = fis.havedefaultchar;
            defaultchar = fis.chardata[0].ch;

            Texture2DDescription desc;
            desc = new Texture2DDescription();
            desc.Width = fis.texturewidth;
            desc.Height = fis.textureheight;
            desc.Format = SlimDX.DXGI.Format.A8_UNorm;
            //tis.mipchain[0].format;  //todo: translate formats (3.1)
            desc.MipLevels = 1;
            desc.OptionFlags = 0;
            desc.BindFlags = BindFlags.ShaderResource;
            desc.CpuAccessFlags = CpuAccessFlags.None;
            desc.SampleDescription = new SlimDX.DXGI.SampleDescription(1, 0);
            desc.Usage = ResourceUsage.Default;
            desc.ArraySize = 1;

            DataRectangle data;
            DataStream datastream = new DataStream(fis.texturedata, true, false);
            data = new DataRectangle(fis.texturewidth, datastream);
            dxtexture = new SlimDX.Direct3D11.Texture2D(device.DX_Device, desc, data);
            dxtextureview = new ShaderResourceView(device.DX_Device, dxtexture);
            texture = new Texture2D(dxtexture, dxtextureview, fis.texturewidth, fis.textureheight);

            int ch;
            firstch = lastch = (int)chardata[0].ch;
            for (int c = 1; c < chardata.Length; c++)
            {
                ch = (int)chardata[c].ch;
                if (ch < firstch) firstch = ch;
                if (ch > lastch) lastch = ch;
            }
            charindex = new int[lastch - firstch + 1];
            for (int i = 0; i < charindex.Length; i++)
                charindex[i] = -1;
            for (int c = 0; c < chardata.Length; c++)
                charindex[((int)chardata[c].ch) - firstch] = c;
        }

        public Microsoft.Xna.Framework.Vector2 MeasureString(string text)
        {
            float x, y, maxx, lastdeltax, maxy;
            x = 0;
            y = 0;
            maxx = 0;
            lastdeltax = 0;
            foreach (char ch in text)
            {
                if (ch == '\r')
                {
                    if (x + lastdeltax > maxx) maxx = x + lastdeltax;
                    x = 0;
                    continue;
                }
                if (ch == '\n')
                {
                    y += LineSpacing;
                    continue;
                }
                int ich = (int)ch;
                if (ich < FirstCh)
                    ich = 0;
                else if (ich > LastCh)
                    ich = 0;
                else
                {
                    ich = CharIndex[ich - FirstCh];
                    if (ich < 0) ich = 0;
                }
                x += ((int)(CharData[ich].stride)) + Spacing;
                lastdeltax = CharData[ich].width - ((int)(CharData[ich].stride));
            }
            if (x + lastdeltax > maxx) maxx = x + lastdeltax;
            maxy = y;
            if (x > 0) maxy += LineSpacing;

            return new Microsoft.Xna.Framework.Vector2(maxx, maxy);
        }

        public Microsoft.Xna.Framework.Vector2 MeasureString(StringBuilder text)
        {
            return MeasureString(text.ToString());
        }

        public void Dispose()
        {
            dxtextureview.Dispose();
            dxtexture.Dispose();
        }
    }
}

// I think this is complete
